package com.geekbg.zookeeper.v20210629;

import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.leader.LeaderLatch;
import org.apache.curator.framework.recipes.leader.LeaderLatchListener;
import org.apache.curator.retry.ExponentialBackoffRetry;

/**
 * @author pizhihui
 * @date 2021-06-29
 */
public class LeaderWatchDemo {

    public static void main(String[] args) throws Exception {

        RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3);

        CuratorFramework client = CuratorFrameworkFactory.builder()
                .connectString("127.0.0.1:2181")
                .retryPolicy(retryPolicy)
                .sessionTimeoutMs(60_000)
                .connectionTimeoutMs(3000)
                .namespace("Global")
                .build();
        client.start();

        LeaderLatch leaderLatch = new LeaderLatch(client, "/zktest/leader", "1233");
        leaderLatch.addListener(new LeaderLatchListener() {
            @Override
            public void isLeader() {
                System.out.println("isLeader");
            }

            @Override
            public void notLeader() {
                System.out.println("no leader");
            }
        });
        leaderLatch.start();


        System.out.println(leaderLatch.hasLeadership());


        System.in.read();

    }

}
